package thulearningcore.util;

import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Hashtable;

public class TLCookieManager {
	private static TLCookieManager instance;
	private Hashtable<String, String> cookieList;

	private TLCookieManager() {
		cookieList = new Hashtable<String, String>();
	}

	public static TLCookieManager getInstance() {
		if (instance == null) {
			instance = new TLCookieManager();
		}
		return instance;
	}

	public void clearCookie() {
		cookieList.clear();
	}

	public void setCookie(String key, String value) {
		cookieList.put(key, value);
	}

	public void addCookieFromURLConnection(URLConnection httpc) {
		String cookieVal = null;
		String key = null, value = null;

		for (int i = 1; (key = httpc.getHeaderFieldKey(i)) != null; i++) {
			if (key.equalsIgnoreCase("set-cookie")) {
				cookieVal = httpc.getHeaderField(i);
				cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
				key = cookieVal.substring(0, cookieVal.indexOf("="));
				value = cookieVal.substring(cookieVal.indexOf("=") + 1,
						cookieVal.length());
				if (key != null && value != null)
					this.setCookie(key, value);
			}
		}
	}

	public String removeCookie(String key) {
		return cookieList.remove(key);
	}

	public String getCookies() {
		if (cookieList.isEmpty())
			return "";
		String c = "";
		String key = null, value = null;
		Enumeration<String> keys = cookieList.keys();
		while (keys.hasMoreElements()) {
			key = keys.nextElement();
			value = cookieList.get(key);
			c = c + key + "=" + value + ";";
		}
		return c;
	}

}
